// 高德地图 Composition API Hook
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import type { Ref } from 'vue'
import type {
    AMapConfig,
    MapOptions,
    DistrictConfig,
    MaskConfig,
    RoadConfig,
    MapState,
    DistrictData,
    DistrictStyle
} from './types'
import {
    loadAMapAPI,
    createMap,
    createDistrictSearch,
    searchDistrict,
    createPolygon,
    clearOverlays,
    fitView,
    formatDistrictData
} from './utils'
import { DistrictManager } from './districtManager'
import { MaskManager } from './maskManager'
import { RoadManager } from './roadManager'

export interface UseAMapOptions {
    mapConfig: AMapConfig
    mapOptions?: Partial<MapOptions>
    districtConfig?: DistrictConfig
    maskConfig?: MaskConfig
    roadConfig?: RoadConfig
    autoInit?: boolean
}

export function useAMap(options: UseAMapOptions) {
    // 响应式状态
    const mapContainer = ref<HTMLElement>()
    const isLoading = ref(false)
    const error = ref<string | null>(null)

    const mapState = reactive<MapState>({
        map: null,
        districtSearch: null,
        currentDistrict: null,
        districtPolygons: [],
        isReady: false,
        maskManager: null,
        roadManager: null
    })

    // 行政区域管理器
    let districtManager: DistrictManager | null = null

    // 当前配置
    const currentConfig = reactive({
        ...options,
        maskConfig: {
            enableMask: true,
            selectedStyle: {
                strokeColor: '#0078ff',
                strokeWeight: 3,
                strokeOpacity: 1,
                fillColor: '#0078ff',
                fillOpacity: 0.4
            },
            unselectedStyle: {
                strokeColor: '#cccccc',
                strokeWeight: 1,
                strokeOpacity: 0.8,
                fillColor: '#f0f0f0',
                fillOpacity: 0.2
            },
            ...options.maskConfig
        },
        roadConfig: {
            showRoads: true,
            roadTypes: ['highway', 'arterial', 'local'],
            roadStyle: {
                strokeColor: '#666666',
                strokeWeight: 2,
                strokeOpacity: 0.8
            },
            ...options.roadConfig
        }
    })

    /**
     * 初始化地图
     */
    const initMap = async () => {
        if (!mapContainer.value) {
            error.value = '地图容器未找到'
            return
        }

        try {
            isLoading.value = true
            error.value = null

            // 加载高德地图API
            await loadAMapAPI({
                ...currentConfig.mapConfig,
                plugins: [
                    'AMap.DistrictSearch',
                    'AMap.Polygon',
                    'AMap.PolyEditor',
                    ...(currentConfig.mapConfig.plugins || [])
                ]
            })

            // 创建地图实例
            mapState.map = createMap({
                container: mapContainer.value,
                ...currentConfig.mapOptions
            })

            // 创建行政区搜索实例
            if (currentConfig.districtConfig) {
                mapState.districtSearch = await createDistrictSearch(currentConfig.districtConfig)

                // 创建行政区域管理器
                districtManager = new DistrictManager(mapState.map, mapState.districtSearch)

                // 创建掩膜管理器
                if (currentConfig.maskConfig) {
                    mapState.maskManager = new MaskManager(mapState.map, currentConfig.maskConfig)
                }

                // 创建道路管理器
                if (currentConfig.roadConfig) {
                    mapState.roadManager = new RoadManager(mapState.map, currentConfig.roadConfig)
                }
            }

            // 绑定地图事件
            bindMapEvents()

            mapState.isReady = true

        } catch (err) {
            error.value = err instanceof Error ? err.message : '地图初始化失败'
            console.error('地图初始化失败:', err)
        } finally {
            console.log('=======================')
            isLoading.value = false
        }
    }

    /**
     * 绑定地图事件
     */
    const bindMapEvents = () => {
        if (!mapState.map) return

        // 地图完成事件
        mapState.map.on('complete', () => {
            console.log('地图加载完成')
        })

        // 地图点击事件
        mapState.map.on('click', (e: any) => {
            console.log('地图点击:', e.lnglat)
        })
    }

    /**
     * 搜索并显示行政区域
     */
    const searchAndShowDistrict = async (keyword: string) => {
        if (!mapState.districtSearch) {
            error.value = '行政区搜索实例未初始化'
            return
        }

        try {
            isLoading.value = true

            const result = await searchDistrict(mapState.districtSearch, keyword)

            if (result.districtList && result.districtList.length > 0) {
                const district = result.districtList[0]
                const formattedDistrict = formatDistrictData(district)

                await showDistrict(formattedDistrict)
                mapState.currentDistrict = formattedDistrict
            } else {
                error.value = `未找到行政区: ${keyword}`
            }
        } catch (err) {
            error.value = err instanceof Error ? err.message : '搜索行政区失败'
            console.error('搜索行政区失败:', err)
        } finally {
            isLoading.value = false
        }
    }

    /**
     * 显示行政区域
     */
    const showDistrict = async (district: DistrictData) => {
        if (!mapState.map || !district.boundaries) return

        // 清除之前的多边形
        clearDistrictPolygons()

        // 创建区域多边形
        district.boundaries.forEach((boundary, index) => {
            const style = currentConfig.maskConfig?.enableMask
                ? currentConfig.maskConfig.selectedStyle
                : {
                    strokeColor: '#0078ff',
                    strokeWeight: 2,
                    strokeOpacity: 1,
                    fillColor: '#0078ff',
                    fillOpacity: 0.3
                }

            const polygon = createPolygon(mapState.map, boundary, style)

            // 绑定多边形点击事件
            polygon.on('click', (e: any) => {
                onDistrictClick(district, e)
            })

            mapState.districtPolygons.push(polygon)
        })

        // 显示子级区域（如果有掩膜效果）
        if (currentConfig.maskConfig?.enableMask && district.children) {
            await showChildDistricts(district.children)
        }

        // 调整地图视野
        fitView(mapState.map, mapState.districtPolygons)

        // 显示道路（如果启用）
        if (currentConfig.roadConfig?.showRoads) {
            showRoadsInDistrict(district)
        }
    }

    /**
     * 显示子级行政区域（用于掩膜效果）
     */
    const showChildDistricts = async (children: DistrictData[]) => {
        if (!mapState.map || !mapState.districtSearch) return

        for (const child of children) {
            try {
                const result = await searchDistrict(mapState.districtSearch, child.name)
                if (result.districtList && result.districtList.length > 0) {
                    const childDistrict = result.districtList[0]

                    if (childDistrict.boundaries) {
                        childDistrict.boundaries.forEach((boundary: any) => {
                            const style = currentConfig.maskConfig?.unselectedStyle || {
                                strokeColor: '#cccccc',
                                strokeWeight: 1,
                                strokeOpacity: 0.8,
                                fillColor: '#f0f0f0',
                                fillOpacity: 0.2
                            }

                            const polygon = createPolygon(mapState.map, boundary, style)

                            // 绑定点击事件
                            polygon.on('click', (e: any) => {
                                onDistrictClick(formatDistrictData(childDistrict), e)
                            })

                            mapState.districtPolygons.push(polygon)
                        })
                    }
                }
            } catch (err) {
                console.warn(`加载子级区域失败: ${child.name}`, err)
            }
        }
    }



    /**
     * 区域点击事件处理
     */
    const onDistrictClick = (district: DistrictData, event: any) => {
        console.log('区域点击:', district.name, event)
        mapState.currentDistrict = district

        // 可以在这里触发自定义事件
        // emit('district-click', district)
    }

    /**
     * 清除区域多边形
     */
    const clearDistrictPolygons = () => {
        clearOverlays(mapState.map, mapState.districtPolygons)
    }

    /**
     * 更新掩膜配置
     */
    const updateMaskConfig = (config: Partial<MaskConfig>) => {
        Object.assign(currentConfig.maskConfig!, config)

        // 重新渲染当前区域
        if (mapState.currentDistrict) {
            showDistrict(mapState.currentDistrict)
        }
    }

    /**
     * 更新道路配置
     */
    const updateRoadConfig = (config: Partial<RoadConfig>) => {
        Object.assign(currentConfig.roadConfig!, config)

        // 重新渲染当前区域
        if (mapState.currentDistrict) {
            showDistrict(mapState.currentDistrict)
        }
    }

    /**
     * 显示省级行政区域
     */
    const showProvinces = async (country: string = '中国') => {
        if (!districtManager) {
            error.value = '行政区域管理器未初始化'
            return []
        }

        try {
            isLoading.value = true
            const provinces = await districtManager.showProvinces(country)
            return provinces
        } catch (err) {
            error.value = err instanceof Error ? err.message : '显示省级区域失败'
            console.error('显示省级区域失败:', err)
            return []
        } finally {
            isLoading.value = false
        }
    }

    /**
     * 显示市级行政区域
     */
    const showCities = async (provinceName: string) => {
        if (!districtManager) {
            error.value = '行政区域管理器未初始化'
            return []
        }

        try {
            isLoading.value = true
            const cities = await districtManager.showCities(provinceName)
            return cities
        } catch (err) {
            error.value = err instanceof Error ? err.message : '显示市级区域失败'
            console.error('显示市级区域失败:', err)
            return []
        } finally {
            isLoading.value = false
        }
    }

    /**
     * 显示区县级行政区域
     */
    const showDistricts = async (cityName: string) => {
        if (!districtManager) {
            error.value = '行政区域管理器未初始化'
            return []
        }

        try {
            isLoading.value = true
            const districts = await districtManager.showDistricts(cityName)
            return districts
        } catch (err) {
            error.value = err instanceof Error ? err.message : '显示区县级区域失败'
            console.error('显示区县级区域失败:', err)
            return []
        } finally {
            isLoading.value = false
        }
    }

    /**
     * 显示指定区域
     */
    const showSpecificDistrict = async (
        keyword: string,
        level: 'province' | 'city' | 'district' = 'city'
    ) => {
        if (!districtManager) {
            error.value = '行政区域管理器未初始化'
            return null
        }

        try {
            isLoading.value = true
            const district = await districtManager.showSpecificDistrict(keyword, level)
            if (district) {
                mapState.currentDistrict = district
            }
            return district
        } catch (err) {
            error.value = err instanceof Error ? err.message : '显示指定区域失败'
            console.error('显示指定区域失败:', err)
            return null
        } finally {
            isLoading.value = false
        }
    }

    /**
     * 返回上一级行政区域
     */
    const goBackLevel = async () => {
        if (!districtManager) {
            error.value = '行政区域管理器未初始化'
            return
        }

        try {
            isLoading.value = true
            await districtManager.goBack()
        } catch (err) {
            error.value = err instanceof Error ? err.message : '返回上一级失败'
            console.error('返回上一级失败:', err)
        } finally {
            isLoading.value = false
        }
    }

    /**
     * 获取当前行政级别
     */
    const getCurrentLevel = () => {
        return districtManager?.getCurrentLevel() || 'province'
    }

    /**
     * 设置行政区域样式
     */
    const setDistrictStyles = (styles: {
        province?: DistrictStyle
        city?: DistrictStyle
        district?: DistrictStyle
    }) => {
        if (districtManager) {
            districtManager.setStyleConfig(styles)
        }
    }

    // ==================== 掩膜相关方法 ====================

    /**
     * 启用/禁用掩膜效果
     */
    const setMaskEnabled = (enabled: boolean) => {
        if (mapState.maskManager) {
            mapState.maskManager.setEnabled(enabled)
        }
    }

    /**
     * 创建省级掩膜效果
     */
    const createProvinceMask = async (selectedProvince: DistrictData, allProvinces?: DistrictData[]) => {
        if (!mapState.maskManager) return

        try {
            // 如果没有提供所有省份数据，则获取全国省份
            if (!allProvinces) {
                allProvinces = await getAllProvinces()
            }

            await mapState.maskManager.createProvinceMask(selectedProvince, allProvinces)
        } catch (error) {
            console.error('创建省级掩膜失败:', error)
        }
    }

    /**
     * 创建城市级掩膜效果
     */
    const createCityMask = async (selectedCity: DistrictData, allCities?: DistrictData[]) => {
        if (!mapState.maskManager) return

        try {
            // 如果没有提供所有城市数据，则根据省份获取城市
            if (!allCities && selectedCity.parent) {
                allCities = await getCitiesByProvince(selectedCity.parent)
            }

            if (allCities) {
                await mapState.maskManager.createCityMask(selectedCity, allCities)
            }
        } catch (error) {
            console.error('创建城市级掩膜失败:', error)
        }
    }

    /**
     * 创建区县级掩膜效果
     */
    const createDistrictMask = async (selectedDistrict: DistrictData, allDistricts?: DistrictData[]) => {
        if (!mapState.maskManager) return

        try {
            // 如果没有提供所有区县数据，则根据城市获取区县
            if (!allDistricts && selectedDistrict.parent) {
                allDistricts = await getDistrictsByCity(selectedDistrict.parent)
            }

            if (allDistricts) {
                await mapState.maskManager.createDistrictMask(selectedDistrict, allDistricts)
            }
        } catch (error) {
            console.error('创建区县级掩膜失败:', error)
        }
    }

    /**
     * 创建自定义掩膜效果
     */
    const createCustomMask = (focusArea: DistrictData | DistrictData[], maskAreas: DistrictData[]) => {
        if (mapState.maskManager) {
            mapState.maskManager.createCustomMask(focusArea, maskAreas)
        }
    }

    /**
     * 更新选中区域样式
     */
    const updateSelectedStyle = (style: Partial<DistrictStyle>) => {
        if (mapState.maskManager) {
            mapState.maskManager.updateSelectedStyle(style)
        }
    }

    /**
     * 更新掩膜区域样式
     */
    const updateMaskStyle = (style: Partial<DistrictStyle>) => {
        if (mapState.maskManager) {
            mapState.maskManager.updateMaskStyle(style)
        }
    }

    /**
     * 清除所有掩膜效果
     */
    const clearMask = () => {
        if (mapState.maskManager) {
            mapState.maskManager.clearMask()
        }
    }

    /**
     * 获取选中的区域
     */
    const getSelectedDistricts = (): DistrictData[] => {
        return mapState.maskManager ? mapState.maskManager.getSelectedDistricts() : []
    }

    /**
     * 获取掩膜区域
     */
    const getMaskDistricts = (): DistrictData[] => {
        return mapState.maskManager ? mapState.maskManager.getMaskDistricts() : []
    }

    /**
     * 调整地图视野以包含掩膜区域
     */
    const fitMaskView = () => {
        if (mapState.maskManager) {
            mapState.maskManager.fitView()
        }
    }

    // ==================== 辅助方法 ====================

    /**
     * 获取全国所有省份
     */
    const getAllProvinces = async (): Promise<DistrictData[]> => {
        if (districtManager) {
            return await districtManager.searchDistrict('中国', 'province')
        }
        return []
    }

    /**
     * 根据省份获取所有城市
     */
    const getCitiesByProvince = async (provinceCode: string): Promise<DistrictData[]> => {
        if (districtManager) {
            return await districtManager.searchDistrict(provinceCode, 'city')
        }
        return []
    }

    /**
     * 根据城市获取所有区县
     */
    const getDistrictsByCity = async (cityCode: string): Promise<DistrictData[]> => {
        if (districtManager) {
            return await districtManager.searchDistrict(cityCode, 'district')
        }
        return []
    }

    // ==================== 道路相关方法 ====================

    /**
     * 启用/禁用道路显示
     */
    const setRoadEnabled = (enabled: boolean) => {
        if (mapState.roadManager) {
            mapState.roadManager.setEnabled(enabled)
        }
    }

    /**
     * 在指定区域内显示道路
     */
    const showRoadsInDistrict = async (district: DistrictData) => {
        if (mapState.roadManager) {
            try {
                await mapState.roadManager.showRoadsInDistrict(district)
            } catch (error) {
                console.error('显示区域道路失败:', error)
            }
        }
    }

    /**
     * 更新道路样式
     */
    const updateRoadStyle = (style: Partial<DistrictStyle>) => {
        if (mapState.roadManager) {
            mapState.roadManager.updateRoadStyle(style)
        }
    }

    /**
     * 设置道路类型显示
     */
    const setRoadTypeVisible = (roadType: string, visible: boolean) => {
        if (mapState.roadManager) {
            mapState.roadManager.setRoadTypeVisible(roadType, visible)
        }
    }

    /**
     * 获取当前显示的道路
     */
    const getCurrentRoads = (): any[] => {
        return mapState.roadManager ? mapState.roadManager.getCurrentRoads() : []
    }

    /**
     * 清除所有道路
     */
    const clearRoads = () => {
        if (mapState.roadManager) {
            mapState.roadManager.clearRoads()
        }
    }

    /**
     * 销毁地图
     */
    const destroyMap = () => {
        if (mapState.roadManager) {
            mapState.roadManager.destroy()
            mapState.roadManager = null
        }

        if (mapState.maskManager) {
            mapState.maskManager.destroy()
            mapState.maskManager = null
        }

        if (districtManager) {
            districtManager.destroy()
            districtManager = null
        }

        if (mapState.map) {
            clearDistrictPolygons()
            mapState.map.destroy()
            mapState.map = null
        }
        mapState.isReady = false
    }

    // 自动初始化
    if (options.autoInit !== false) {
        onMounted(async () => {
            await nextTick()
            await initMap()
        })
    }

    // 组件卸载时清理
    onUnmounted(() => {
        destroyMap()
    })

    return {
        // 响应式状态
        mapContainer,
        isLoading,
        error,
        mapState,
        currentConfig,

        // 基础方法
        initMap,
        destroyMap,

        // 原有方法（兼容性）
        searchAndShowDistrict,
        showDistrict,
        clearDistrictPolygons,
        updateMaskConfig,
        updateRoadConfig,

        // 新增的行政区域方法
        showProvinces,
        showCities,
        showDistricts,
        // 兼容性别名
        showProvinceDistricts: showProvinces,
        showCityDistricts: showCities,
        showDistrictDistricts: showDistricts,
        showSpecificDistrict,
        goBackLevel,
        goBackToPreviousLevel: goBackLevel,
        getCurrentLevel,
        setDistrictStyles,

        // 掩膜方法
        setMaskEnabled,
        createProvinceMask,
        createCityMask,
        createDistrictMask,
        createCustomMask,
        updateSelectedStyle,
        updateMaskStyle,
        clearMask,
        getSelectedDistricts,
        getMaskDistricts,
        fitMaskView,

        // 辅助方法
        getAllProvinces,
        getCitiesByProvince,
        getDistrictsByCity,

        // 道路方法
        setRoadEnabled,
        showRoadsInDistrict,
        updateRoadStyle,
        setRoadTypeVisible,
        getCurrentRoads,
        clearRoads
    }
}